package com.zhiming.item.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhiming.common.exception.pojo.ExceptionEnum;
import com.zhiming.common.exception.pojo.ZmException;
import com.zhiming.common.pojo.PageResult;
import com.zhiming.item.mapper.ArticleMapper;
import com.zhiming.item.mapper.MenuMapper;
import com.zhiming.item.pojo.Article;
import com.zhiming.item.pojo.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 文章 Service
 */

@Service
public class ArticleService {
    @Autowired(required = false)
    private ArticleMapper articleMapper;
    @Autowired(required = false)
    private MenuMapper menuMapper;

    /**
     * 根据id查询文章
     */
    public Article findById(Integer id) {
        //根据文章id查询文章信息
        QueryWrapper<Article> queryWrapper = Wrappers.query();
        queryWrapper.eq("id",id);
        queryWrapper.select("id","title","content","menu_id");

        Article article = articleMapper.selectOne(queryWrapper);
        if(article == null){
            throw new ZmException(ExceptionEnum.ARTICLE_NOT_FOUND);
        }

        //通过导航id查询导航名称
        Menu menu = menuMapper.selectById(article.getMenuId());
        //添加导航名称
        article.setMenuName(menu.getCname());

        return article;
    }

    /**
     * 动态分页查询文章
     */
    public PageResult<Article> articlePageQuery(Integer currentPage, Integer pageSize,Integer menu_id,String title) {
        //1.封装分页条件
        IPage<Article> iPage = new Page(currentPage,pageSize);
        QueryWrapper<Article> queryWrapper = Wrappers.query();


        //过滤匹配该导航下的文章(如果导航id存在)
        if(menu_id != null){
            queryWrapper.eq("menu_id",menu_id);
        }
        //模糊查询文章标题(如果标题参数存在)
        if(StringUtils.isNotEmpty(title)){
            queryWrapper.like("title",title);
        }

        //过滤状态为已发布的文章(status=0 表示已发布)
        queryWrapper.eq("status",0);

        //过滤只要id,title字段的内容
        queryWrapper.select("id","title","menu_id");

        //2.执行查询，获取结果
        iPage = articleMapper.selectPage(iPage, queryWrapper);

        //3.取出所有文章数据
        List<Article> articleList = iPage.getRecords();

        //4.封装PageResult分页对象
        PageResult<Article> pageResult = new PageResult<>(iPage.getTotal(), iPage.getPages(), articleList);

        //5.返回
        return pageResult;
    }

    //查询最新的10篇文章
    public List<Article> getNewestArticle() {
        QueryWrapper<Article> queryWrapper = Wrappers.query();
        queryWrapper.select("id","title").orderByDesc("create_time").last("limit 10");

        List<Article> articles = articleMapper.selectList(queryWrapper);
        return articles;
    }
}
